package controllers

import (
	"cronjob/libs"
	"cronjob/models"
	"strconv"
	"strings"

	"github.com/astaxie/beego"
)

const (
	//成功
	MSG_OK = 0
	//失败
	MSG_ERR = -1
)

type BaseController struct {
	beego.Controller
	controllerName string //控制器名
	actionName     string // 方法名

	userID int
	user   *models.Admin

	serverGroups string //服务器分组id
	taskGroups   string //任务分组id

	pageSize int //每页显示数量
}

func (this *BaseController) Prepare() {

	//获取控制器名称和方法名称  IndexController_Index.html
	//IndexController  LinkController TagController
	controllerName, actionName := this.GetControllerAndAction()
	//去除控制器名称尾部的Controller并将结果转换为小写
	this.controllerName = strings.ToLower(controllerName[:len(controllerName)-10])
	//将方法名称转换为小写
	this.actionName = strings.ToLower(actionName)

	this.Auth()
}

//ajax 返回值
func (this *BaseController) ajaxMsg(msg interface{}, msgno int) {
	data := make(map[string]interface{})
	data["status"] = msgno
	data["message"] = msg

	this.Data["json"] = data
	this.ServeJSON()
	// this.StopRun()
}

func (this *BaseController) display(tpl ...string) {
	var tplname string
	if len(tpl) > 0 {
		tplname = strings.Join([]string{tpl[0], "html"}, ".")
	} else {
		tplname = this.controllerName + "/" + this.actionName + ".html"
	}

	this.Layout = "public/layout.html"
	this.TplName = tplname
}

//返回客户端ip
func (this *BaseController) getClientIP() string {
	arrIP := strings.Split(this.Ctx.Request.RemoteAddr, ":")
	// beego.Info(arrIP)

	return arrIP[0]
}

//验证用户是否登录
func (this *BaseController) Auth() {
	// 获取cookie 并分割
	arr := strings.Split(this.Ctx.GetCookie("auth"), "|")

	if len(arr) == 2 {
		idstr, authstr := arr[0], arr[1]
		//将字符串id转化成userId
		userId, _ := strconv.Atoi(idstr)
		if userId > 0 {
			userInfo, err := models.AdminGetById(userId)
			if err == nil && authstr == libs.MD5([]byte(this.getClientIP()+"|"+userInfo.Salt)) {
				this.userID = userId
				this.user = userInfo

				//显示登录用户名
				this.Data["loginUserName"] = userInfo.LoginName

				//加载菜单
				this.AdminAuth()

				//加载服务器分组id
			}
		}

	} else {
		if this.controllerName != "login" && this.actionName != "login" {
			this.Redirect(beego.URLFor("LoginController.Login"), 302)
		}
	}
}

func (this *BaseController) dataAuth(user *models.Admin) {
	// 不能等于默认值和空值
	if user.RoleIds == "" || user.RoleIds == "0" {
		return
	}

	filters := make([]interface{}, 0)

	filters = append(filters, "status", 1)

	RoleIdsArr := strings.Split(user.RoleIds, ",")

	//将字符串类型的RoleIdsArr转换为整形
	RoleIds := make([]int, 0)
	for _, v := range RoleIdsArr {
		id, _ := strconv.Atoi(v)
		RoleIds = append(RoleIds, id)
	}

	//
	Result, _ := models.RoleGetList(1, 1000, filters...)
	serverGroups := ""
	taskGroups := ""

	//拼接服务器id
	for _, v := range Result {
		serverGroups += v.ServerGroupIds + ","
		taskGroups += v.TaskGroupIds + ","
	}

	this.serverGroups = strings.TrimRight(serverGroups, ",")
	this.taskGroups = strings.TrimRight(taskGroups, ",")

}

//authStr:服务器分组id
//adminId:管理员id
func serverGroupLists(authStr string, adminId int) (sgl map[int]string) {
	Filters := make([]interface{}, 0)
	Filters = append(Filters, "status", 1)
	//服务器分组id不为空并且不是超级管理员
	if authStr != "" && adminId != 1 {
		//通过逗号进行切割
		serverGroupIdsArr := strings.Split(authStr, ",")
		serverGroupIds := make([]int, 0)
		for _, v := range serverGroupIdsArr {
			id, _ := strconv.Atoi(v)
			serverGroupIds = append(serverGroupIds, id)
		}
		Filters = append(Filters, "id__in", serverGroupIds)
	}
	//分页查询
	groupResult, n := models.ServerGroupGetList(1, 1000, Filters...)
	sgl = make(map[int]string, n)
	//遍历服务器分组切片，将其中值封装到map中
	for _, gv := range groupResult {
		sgl[gv.Id] = gv.GroupName
	}
	return sgl
}

// 获取任务分组

func taskGroupLists(authstr string, adminId int) map[int]string {
	groupFilters := make([]interface{}, 0)
	groupFilters = append(groupFilters, "status", 1)
	//判断authstr不是空字符串并且当前不是超级管理员
	if authstr != "" && adminId != 1 {
		//1,2,3
		//通过逗号切割
		taskGroupIdArr := strings.Split(authstr, ",")
		//将字符串分组id转换为整形分组id
		taskGroupId := make([]int, 0)
		for _, v := range taskGroupIdArr {
			id, _ := strconv.Atoi(v)
			taskGroupId = append(taskGroupId, id)
		}
		//  1,2,3
		groupFilters = append(groupFilters, "id__in", taskGroupId)
	}
	//分页查询
	groupResult, n := models.GroupGetList(1, 10000, groupFilters...)
	gl := make(map[int]string, n)
	for _, gv := range groupResult {
		gl[gv.Id] = gv.GroupName
	}
	return gl
}

//加载菜单
func (this *BaseController) AdminAuth() {
	//创建切片存储过滤切片
	filters := make([]interface{}, 0)

	//正常状态的权限
	filters = append(filters, "Status", 1)

	//判断是否为超级管理员
	if this.userID != 1 {
		adminAuthIds, _ := models.RoleAuthGetByIds(this.user.RoleIds)

		beego.Info(adminAuthIds)
		// 将字符串转化成切片
		adminAuthIdsArr := strings.Split(adminAuthIds, ",")
		filters = append(filters, "id__in", adminAuthIdsArr)
	}

	result, _ := models.AuthGetList(1, 1000, filters...)

	// beego.Info(len(result))
	//一级菜单
	list := make([]map[string]interface{}, len(result))
	//二级菜单
	list2 := make([]map[string]interface{}, len(result))
	i, j := 0, 0
	//遍历结果切片

	for _, v := range result {
		//创建map，用于存储每一记录
		row := make(map[string]interface{})
		//判断父级id是否为1并且isshow是否为1
		//一级菜单
		if v.Pid == 1 && v.IsShow == 1 {
			row["Icon"] = v.Icon
			row["AuthName"] = v.AuthName
			row["Id"] = v.Id
			list[i] = row
			i++
		}
		//二级菜单
		if v.Pid != 1 && v.IsShow == 1 {
			row["Pid"] = v.Pid
			row["AuthUrl"] = v.AuthUrl
			row["Icon"] = v.Icon
			row["AuthName"] = v.AuthName
			row["Id"] = v.Id
			list2[j] = row
			j++
		}
	}

	//不到忘记切割
	this.Data["SideMenu1"] = list[:i]
	this.Data["SideMenu2"] = list2[:j]
}

/*
{
  "code": 0,
  "msg": "",
  "count": 1000,
  "data": [{}, {}]
}
*/
//ajax返回
func (this *BaseController) ajaxList(msg interface{}, msgno int, count int64, data interface{}) {
	out := make(map[string]interface{})
	out["code"] = msgno
	out["msg"] = msg
	out["count"] = count
	out["data"] = data
	this.Data["json"] = out
	this.ServeJSON()
	//  this.StopRun()
}

type serverList struct {
	GroupId int
	//服务器分组名称
	GroupName string //A     B
	//服务器  map[id]name
	Servers map[int]string //{[1,测试服务器], [2, 远程服务器]}  {[1,测试服务器], [2, 远程服务器]}
}

// 获取服务器分组信息
func serverLists(authStr string, adminId int) (sls []serverList) {
	// 服务器分组
	serverGroup := serverGroupLists(authStr, adminId)

	for k, val := range serverGroup {
		sl := serverList{}
		sl.GroupId = k
		sl.GroupName = val

		Result := models.TaskServersByGroupId(k)
		servers := make(map[int]string)
		for _, sval := range Result {
			servers[sval.Id] = sval.ServerName
		}
		sl.Servers = servers

		sls = append(sls, sl)

	}

	return sls

}
